#include "seatselect.h"
#include "ui_seatselect.h"
#include "reservehome.h"
#include "seatreserve.h"
#include "seatshow.h"
#include "QMouseEvent"
#include <QDebug>
#include <QDate>
#include <QMessageBox>
#include <QCheckBox>
QString seatSelect::seatName="";
seatSelect::seatSelect(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::seatSelect)
{
    ui->setupUi(this);
    this->setWindowFlags(Qt::FramelessWindowHint); // 设置窗口无边框

    // 获取今天的日期
    QDate today = QDate::currentDate();
    // 获取明天的日期
    QDate tomorrow = today.addDays(1);

    ui->pushButton_4->setText(today.toString("yyyy-MM-dd"));
    ui->pushButton_5->setText(tomorrow.toString("yyyy-MM-dd"));


    int c=reserveHome::index_campus;
    int f=reserveHome::index_floor;
    int a=reserveHome::index_area;
    ui->label_2->setText(reserveHome::campuses[c].name+"-"+reserveHome::campuses[c].f[f].name+"-"+reserveHome::campuses[c].f[f].a[a].name);
    area theArea=reserveHome::campuses[c].f[f].a[a];
    int num=0;
    for (int i = 0; i < theArea.seatNum; ++i) {
        if(theArea.s[i].isUnbooked){
        // 创建按钮
        QPushButton *button = new QPushButton(theArea.s[i].name, this);
            // 设置按钮样式
        button->setStyleSheet(
            "QPushButton {"
            "    color: #000000;" /* 黑色 */
            "    border: 2px solid #e0FFFF;" /* 边框 */
            "    border-radius: 10px;" /* 设置圆角半径为20像素 */

            "    height: 40px;"
            "}"
            "QPushButton:hover {"
            "    color: #00FF00;" /* 绿色 */
            "    border: 2px solid #e0FFFF;" /* 边框 */
            "    border-radius: 10px;" /* 保持圆角半径为20像素 */

            "    height: 40px;"
            "}"
            "QPushButton:pressed {"
            "    color: #FF0000;" /* 红色 */
            "    border: 2px solid #e0FFFF;" /* 边框 */
            "    border-radius: 10px;" /* 保持圆角半径为20像素 */

            "    height: 40px;"
            "}"
        );

        // 计算行列位置
        int row = num / 5;  // 每行5个按钮，所以用索引除以5得到行号
        int col = num % 5;  // 用索引对5取余得到列号

        // 添加按钮到布局中
        ui->seatLayout->addWidget(button, row, col);
        // 连接按钮点击信号，并传递i作为参数
        connect(button, &QPushButton::clicked, [=]() {onSeatClicked(i, button); });
        ++num;
        }
    }
    // 获取seatLayout中的所有QPushButton控件
        QLayout *layout = ui->seatLayout;
        QList<QPushButton*> buttons;
        for (int i = 0; i < layout->count(); ++i) {
            QWidget *widget = layout->itemAt(i)->widget();
            if (QPushButton *button = qobject_cast<QPushButton*>(widget)) {
                buttons.append(button);
            }
      }
        emit buttons[0]->click();
}

seatSelect::~seatSelect()
{
    delete ui;
}

QPoint initialMousePosition;
bool isDragging = false;

void seatSelect::onSeatClicked(int index,QPushButton *button) {
    seat_selected=true;
    for (int i = 0; i < ui->seatLayout->count(); ++i) {
            QLayoutItem *item = ui->seatLayout->itemAt(i);
            if (item) {
                // 获取布局项对应的控件
                QWidget *widget = item->widget();
                if (widget) {
                    // 检查控件是否是QPushButton的实例
                    QPushButton *button = qobject_cast<QPushButton *>(widget);
                    if (button) {
                        // 如果是QPushButton，设置样式表
                        button->setStyleSheet(basicStyle+"QPushButton{background-color:white;}");
                    }
                }
            }
        }
    button->setStyleSheet(basicStyle+"QPushButton{background-color:blue;}");
    reserveHome::choice=index;
    qDebug()<<reserveHome::choice;
    int m=index+1;
    ui->label_4->setText(QString("当前选择 座位%1").arg(m));
    reserveHome::booked=true;

}
void seatSelect::on_pushButton_7_clicked()
{
    //更新座位信息,应对中途其他用户预约的状况
    reserveHome::importJsonToCampuses("D:\\QtCode\\Library_System_1\\library_seats.json",reserveHome::campuses);
    int c=reserveHome::index_campus;
    int f=reserveHome::index_floor;
    int a=reserveHome::index_area;
    int s = reserveHome::choice;


    // 获取校区、楼层、区域和座位的具体信息
    QString campusName = reserveHome::campuses[c].name;
    QString floorName = reserveHome::campuses[c].f[f].name;
    QString areaName = reserveHome::campuses[c].f[f].a[a].name;
    QString seatName = reserveHome::campuses[c].f[f].a[a].s[s].name;

    // 拼接预约信息
    QString reservationInfo = QString("%1-%2-%3-%4").arg(campusName).arg(floorName).arg(areaName).arg(seatName);
    QTime currentTime = QTime::currentTime();
    QString currentTimeString = currentTime.toString("HH:mm:ss");
    if(!seat_selected){
            // 创建一个 QMessageBox 对象
            QMessageBox messageBox;
            // 设置消息框的标题
            messageBox.setWindowTitle("提示");
            // 设置消息框的内容
            messageBox.setText("您还没有选择座位");
            // 设置消息框中的按钮
            messageBox.setStandardButtons(QMessageBox::Yes);
            // 设置消息框的图标
            messageBox.setIcon(QMessageBox::Warning);
            // 显示消息框，并等待用户响应
            messageBox.exec();
        }
    else if(!reserveHome::campuses[c].f[f].a[a].s[s].isUnbooked){
        // 创建一个 QMessageBox 对象
        QMessageBox messageBox;
        // 设置消息框的标题
        messageBox.setWindowTitle("提示");
        // 设置消息框的内容
        messageBox.setText("该座位已被预约");
        // 设置消息框中的按钮
        messageBox.setStandardButtons(QMessageBox::Yes);
        // 设置消息框的图标
        messageBox.setIcon(QMessageBox::Warning);
        // 显示消息框，并等待用户响应
        messageBox.exec();
        return;
    }
    else if(data == ui->pushButton_4->text()){
        reserveHome::isToday = true;
        // 在当前时间上加一个小时
        QTime newTime = currentTime.addSecs(3600);
        QString newTimeString = newTime.toString("HH:mm:ss");
        timeString = data + " " + newTimeString;
        worktimeString =  ui->pushButton_4->text() + " " + currentTimeString;
        reserveHome::reserveTime = timeString;
        QString reserveInformation = "位置：" + reservationInfo + " 预约时间：" + timeString + " 操作时间：" + worktimeString;
        reserveHome::history[reserveHome::historyNum++] =  reserveInformation;
        reserveHome*r=new reserveHome;
        r->show();
        //将预约信息保存回文件
        //更改为已经预约
        reserveHome::campuses[c].f[f].a[a].s[reserveHome::choice].isUnbooked=false;
        reserveHome::saveCampusesToJson(reserveHome::campuses,"D:\\QtCode\\Library_System_1\\library_seats.json");
        this->close();
    }else if(data == ui->pushButton_5->text()){
        reserveHome::isToday = false;
        timeString = data + " 8:00:00";
        worktimeString =  ui->pushButton_4->text() + " " + currentTimeString;
        reserveHome::reserveTime = timeString;
        QString reserveInformation = "位置：" + reservationInfo + " 预约时间：" + timeString + " 操作时间：" + worktimeString;
        reserveHome::history[reserveHome::historyNum++] =  reserveInformation;
        reserveHome*r=new reserveHome;
        r->show();
        //将预约信息保存回文件
        //更改为已经预约
        reserveHome::campuses[c].f[f].a[a].s[reserveHome::choice].isUnbooked=false;

        reserveHome::saveCampusesToJson(reserveHome::campuses,"D:\\QtCode\\Library_System_1\\library_seats.json");
        this->close();
    }
    else{
        // 创建一个 QMessageBox 对象
        QMessageBox messageBox;
        // 设置消息框的标题
        messageBox.setWindowTitle("提示");
        // 设置消息框的内容
        messageBox.setText("您还没有选择预约时间");
        // 设置消息框中的按钮
        messageBox.setStandardButtons(QMessageBox::Yes);
        // 设置消息框的图标
        messageBox.setIcon(QMessageBox::Warning);
        // 显示消息框，并等待用户响应
        messageBox.exec();
    }
}

void seatSelect::on_pushButton_clicked()
{
    seatReserve*s=new seatReserve;
    s->show();
    this->close();
}
void seatSelect::mousePressEvent(QMouseEvent *event) {
    if (event->button() == Qt::LeftButton) {
                initialMousePosition = event->globalPos(); // 记录鼠标按下时的全局位置
                isDragging = true; // 开始拖动
            }
    }

void seatSelect::mouseMoveEvent(QMouseEvent *event){
    if (isDragging && event->buttons() & Qt::LeftButton) {
                QPoint delta = event->globalPos() - initialMousePosition; // 计算鼠标移动的距离
                move(x() + delta.x(), y() + delta.y()); // 根据鼠标移动的距离来移动窗口
                initialMousePosition = event->globalPos(); // 更新鼠标位置
            }
    }
void seatSelect::mouseReleaseEvent(QMouseEvent *event) {
        if (event->button() == Qt::LeftButton) {
            isDragging = false; // 结束拖动
        }
    }


void seatSelect::on_pushButton_2_clicked()
{
    reserveHome*r=new reserveHome;
    r->show();
    this->close();
}

void seatSelect::on_pushButton_3_clicked()
{
    seatshow *r = new seatshow;
    r->s=this;
    r->show();
}
void seatSelect::handleSeatClose(int index){
    qDebug()<<"handling";
    QPushButton *theButton=new QPushButton ;
    int i;
    for (i = 0; i < ui->seatLayout->count(); ++i) {
            QLayoutItem *item = ui->seatLayout->itemAt(i);
            if (item) {
                // 获取布局项对应的控件
                QWidget *widget = item->widget();
                if (widget) {
                    // 检查控件是否是QPushButton的实例
                    QPushButton *button = qobject_cast<QPushButton *>(widget);
                    if (button) {
                        // 如果是QPushButton，设置样式表
                       if( button->text()==seatName){
                           theButton=button;
                           break;
                       }
                    }
                }
            }
        }
    onSeatClicked(index,theButton);
}
void seatSelect::on_pushButton_4_clicked()
{
     ui->pushButton_4->setStyleSheet(basicStyle2+"QPushButton{background-color:blue;}");
     ui->pushButton_5->setStyleSheet(basicStyle+"QPushButton{background-color:white;}");
    if(reserveHome::isMessageShowAgain){
        // 创建一个QMessageBox对象
        QMessageBox messageBox;
        messageBox.setWindowTitle("温馨提示");
        messageBox.setText("预约当天请在预约后60分钟内到馆");

        // 设置消息类型
        messageBox.setIcon(QMessageBox::Information);

        // 设置按钮
        QPushButton *okButton = messageBox.addButton(QMessageBox::Ok);
        messageBox.setDefaultButton(okButton);

        // 创建一个QCheckBox
        QCheckBox *checkBox = new QCheckBox("Do not show again", &messageBox);
        messageBox.setCheckBox(checkBox);

        // 连接复选框的stateChanged信号到槽函数
        connect(checkBox, &QCheckBox::stateChanged, this, &seatSelect::on_checkBoxStateChanged);

        // 显示消息框
        messageBox.exec();
    }
    data = ui->pushButton_4->text();
    ui->label_6->setText("当前选择：" + data);
}

void seatSelect::on_pushButton_5_clicked()
{
    ui->pushButton_4->setStyleSheet(basicStyle2+"QPushButton{background-color:white;}");
    ui->pushButton_5->setStyleSheet(basicStyle+"QPushButton{background-color:blue;}");
    if(reserveHome::isMessageShowAgain2){
        // 创建一个QMessageBox对象
        QMessageBox messageBox;
        messageBox.setWindowTitle("Message Box");
        messageBox.setText("预约次日请在次日早上8：00前到馆");

        // 设置消息类型
        messageBox.setIcon(QMessageBox::Information);

        // 设置按钮
        QPushButton *okButton = messageBox.addButton(QMessageBox::Ok);
        messageBox.setDefaultButton(okButton);

        // 创建一个QCheckBox
        QCheckBox *checkBox = new QCheckBox("Do not show again", &messageBox);
        messageBox.setCheckBox(checkBox);

        // 连接复选框的stateChanged信号到槽函数
        connect(checkBox, &QCheckBox::stateChanged, this, &seatSelect::on_checkBoxStateChanged2);

        // 显示消息框并获取用户选择
        int ret = messageBox.exec();

        // 根据返回值判断用户点击了哪个按钮
        if (ret == QMessageBox::Ok) {
            // 用户点击了OK按钮
            bool checked = checkBox->isChecked();
            if(checked){

            }
        }
    }
    data = ui->pushButton_5->text();
    ui->label_6->setText("当前选择：" + data);
}

void seatSelect::on_checkBoxStateChanged(int state)
{
    if (state == Qt::Checked) {
        // 用户勾选了复选框，执行相应的操作
        reserveHome::isMessageShowAgain = false;
    } else {
        // 用户取消了勾选
        reserveHome::isMessageShowAgain = true;
    }
}

void seatSelect::on_checkBoxStateChanged2(int state)
{
    if (state == Qt::Checked) {
        // 用户勾选了复选框，执行相应的操作
        reserveHome::isMessageShowAgain2 = false;
    } else {
        // 用户取消了勾选
        reserveHome::isMessageShowAgain2 = true;
    }
}
void seatSelect::updateSeats(){
    //更新座位信息
    reserveHome::importJsonToCampuses("D:\\QtCode\\Library_System_1\\library_seats.json",reserveHome::campuses);
    //清空按钮
    QLayoutItem *item;
        while ((item = ui->seatLayout->takeAt(0))) {
            if (QPushButton *button = qobject_cast<QPushButton*>(item->widget())) {
                delete button;
            }
            delete item;
        }
    //重新布置
    int c=reserveHome::index_campus;
    int f=reserveHome::index_floor;
    int a=reserveHome::index_area;
    ui->label_2->setText(reserveHome::campuses[c].name+"-"+reserveHome::campuses[c].f[f].name+"-"+reserveHome::campuses[c].f[f].a[a].name);
    area theArea=reserveHome::campuses[c].f[f].a[a];
    int num=0;
    for (int i = 0; i < theArea.seatNum; ++i) {
        if(theArea.s[i].isUnbooked){
        // 创建按钮
        QPushButton *button = new QPushButton(theArea.s[i].name, this);
            // 设置按钮样式
        button->setStyleSheet(
            "QPushButton {"
            "    color: #000000;" /* 黑色 */
            "    border: 2px solid #e0FFFF;" /* 边框 */
            "    border-radius: 10px;" /* 设置圆角半径为20像素 */

            "    height: 40px;"
            "}"
            "QPushButton:hover {"
            "    color: #00FF00;" /* 绿色 */
            "    border: 2px solid #e0FFFF;" /* 边框 */
            "    border-radius: 10px;" /* 保持圆角半径为20像素 */

            "    height: 40px;"
            "}"
            "QPushButton:pressed {"
            "    color: #FF0000;" /* 红色 */
            "    border: 2px solid #e0FFFF;" /* 边框 */
            "    border-radius: 10px;" /* 保持圆角半径为20像素 */

            "    height: 40px;"
            "}"
        );

        // 计算行列位置
        int row = num / 5;  // 每行5个按钮，所以用索引除以5得到行号
        int col = num % 5;  // 用索引对5取余得到列号

        // 添加按钮到布局中
        ui->seatLayout->addWidget(button, row, col);
        // 连接按钮点击信号，并传递i作为参数
        connect(button, &QPushButton::clicked, [=]() {onSeatClicked(i, button); });
        ++num;
        }
    }
}
void seatSelect::on_pushButton_6_clicked()
{
    updateSeats();
}

void seatSelect::keyPressEvent(QKeyEvent *event){
    // 获取seatLayout中的所有QPushButton控件
        QLayout *layout = ui->seatLayout;
        QList<QPushButton*> buttons;
        for (int i = 0; i < layout->count(); ++i) {
            QWidget *widget = layout->itemAt(i)->widget();
            if (QPushButton *button = qobject_cast<QPushButton*>(widget)) {
                buttons.append(button);
            }
      }
        switch (event->key()) {
        case Qt::Key_W:
            newIndex -= ui->seatLayout->columnCount();
            break;
        case Qt::Key_A:
            newIndex -= 1;
            break;
        case Qt::Key_S:
            newIndex += ui->seatLayout->columnCount();
            break;
        case Qt::Key_D:
            newIndex += 1;
            break;
        case Qt::Key_Enter:
        case Qt::Key_Return:
            emit ui->pushButton_7->click();
            return;
        default:
            //seatReserve::keyPressEvent(event);
            return;
        }

        if (newIndex >= 0 && newIndex < buttons.size()) {
            //reserveHome::choice = newIndex;
            // 模拟按钮点击事件
            qDebug()<<"newIndex:"<<newIndex;
            QPushButton *button = buttons[newIndex];
            QMetaObject::invokeMethod(button, "click", Qt::QueuedConnection);
        }
}
